package com.samuel.blog.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.samuel.blog.constant.CommonConstant;

/**
 * 登录拦截器
 * @author 开机
 * @date 2017-12-28
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 访问controller之前
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String contextPath = request.getContextPath();
		
		// 获取login用户的session
		Object author = request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION_KEY);
		if (author != null) {
			return true;
		} else {
			// 跳转
			response.sendRedirect(contextPath+"/admin/author/login.html");
			return false;
		}
	}
	
	/**
	 * 访问controller之后 但是在返回页面之前
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 整个请求处理完毕回调方法，即在视图渲染完毕时回调
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 处理异步请求
	 *  过程  preHandle - afterConcurrentHandlingStarted - preHandle - postHandle - afterCompletion
	 */
	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

}
